<?php

namespace app\store\controller\setting;

use app\store\controller\Controller;
use app\store\model\Region as RegionModel;

/**
 * 城市
 * Class Delivery
 * @package app\store\controller\setting
 */
class Region extends Controller
{
    /**
     * 城市列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $list = RegionModel::getCityList($this->request->param());
        return $this->fetch('index', compact('list'));
    }

    /**
     * 添加城市
     * @return array|mixed
     */
    public function add()
    {
        // 新增记录
        $model = new RegionModel;
        if (!$this->request->isAjax()) {
            // 获取所有地区
            $list = $model::getCacheTree();
            return $this->fetch('add', compact('list'));
        }
        if ($model->add($this->postData('region'))) {
            return $this->renderSuccess('添加成功', url('setting.region/index'));
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    /**
     * 编辑城市
     * @param $Region_id
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function edit($city_id)
    {
        // 模板详情
        $model = RegionModel::getModel($city_id);
        if (!$this->request->isAjax()) {
             // 获取所有地区
            $list = $model::getCacheTree();
            return $this->fetch('edit', compact('model','list'));
        }
        // 更新记录
        if ($model->edit($this->postData('region'))) {
            return $this->renderSuccess('更新成功', url('setting.region/index'));
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /**
     * 设置状态
     */
    public function state($city_id, $state)
    {
        $model = RegionModel::getModel($city_id);
        if (!$model->setStatus($state)) {
            return $this->renderError('操作失败');
        }
        return $this->renderSuccess('操作成功');
    }

    /**
     * 删除城市
     * @param $city_id
     * @return array
     * @throws \think\exception\DbException
     */
    public function delete($city_id)
    {
        $model = RegionModel::getModel($city_id);
        if (!$model->remove($city_id)) {
            return $this->renderError($model->getError() ?: '删除失败');
        }
        return $this->renderSuccess('删除成功');
    }

    public function cityList()
    {
        $list = RegionModel::getPublicCity();
        if (!$list) {
            return $this->renderError('没有城市');
        }
        return $this->renderSuccess('成功','', $list);
    }

}
